import type { ProFormInstance } from '@ant-design/pro-components';
import {
  ProForm,
  ProFormDigit,
  ProFormGroup,
  ProFormMoney,
  ProFormRadio,
  ProFormText,
  ProFormTextArea,
  ProFormTreeSelect,
} from '@ant-design/pro-components';
import { useNavigate, useParams } from '@umijs/max';
import { Divider, Form, message } from 'antd';
import { useRef } from 'react';
import FileUploader from '@/components/UploadFile';
import {
  createManagement,
  managementDetail,
  typeCategories,
  updateManagement,
} from '@/services/mall/api';

export default () => {
  const formRef = useRef<ProFormInstance<ProductType.ManagementDetail>>(null);
  const { id } = useParams<{ id?: string }>();
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const isEdit = !!id;

  return (
    <ProForm<ProductType.ManagementDetail>
      form={form}
      onFinish={async (values) => {
        const submitData = isEdit ? { ...values, id: Number(id) } : values;
        isEdit
          ? await updateManagement(submitData)
          : await createManagement(submitData);
        message.success(isEdit ? '更新成功' : '保存成功');
        navigate(-1);
      }}
      formRef={formRef}
      // 仅在编辑模式下传递id参数
      params={isEdit ? { id } : undefined}
      formKey="base-form-use-demo"
      // 根据是否有id决定是否请求详情数据
      request={async () => {
        if (isEdit) {
          // 编辑：返回详情
          return await managementDetail(id);
        } else {
          // 新增：返回默认值
          return {
            type: 1,
            isRecommended: 1,
            isDisplayed: 1,
            status: 1,
          };
        }
      }}
      autoFocusFirstInput
      submitter={{
        searchConfig: { submitText: isEdit ? '更新' : '保存' },
      }}
    >
      {/* 基础信息分组 */}
      <ProFormGroup title="基础信息">
        <ProFormTreeSelect
          width={'lg'}
          label="商品分类"
          name="productType"
          request={async () => {
            return await typeCategories();
          }}
        />

        <ProFormText name="productBarcode" label="商品条码" />
        <ProFormText name="productName" label="商品名称" />
        <ProFormText name="alias" label="别名" />
        <ProFormText name="tagKeywords" label="标签" />

        <ProFormRadio.Group
          label="类型"
          name="type"
          options={[
            { label: '实物商品', value: 1 },
            { label: '虚拟商品', value: 2 },
          ]}
        />
      </ProFormGroup>

      <Divider style={{ margin: '24px 0' }} />

      {/* 描述信息分组 */}
      <ProFormGroup title="描述信息">
        <ProFormTextArea
          width="xl"
          name="productFeatures"
          label="详细描述"
          placeholder="请输入商品详细描述"
          fieldProps={{
            maxLength: 100,
            showCount: true,
          }}
        />
        <ProFormTextArea
          width="xl"
          name="purchaseNotice"
          label="购买须知"
          placeholder="请输入购买须知"
          fieldProps={{
            maxLength: 100,
            showCount: true,
          }}
        />
      </ProFormGroup>

      <Divider style={{ margin: '24px 0' }} />

      {/* 媒体信息 */}
      <ProFormGroup title="媒体信息">
        <ProForm.Item
          name="productImages"
          label="商品图片"
          valuePropName="value"
          trigger="onChange"
        >
          <FileUploader
            listType="picture-card"
            fileType="image"
            useBase64={true}
            maxCount={1}
            showPreview={true}
            // value={productImagesValue || ""}
            // onChange={(value) => {
            //   form.setFieldValue("productImages", value ?? "");
            // }}
          />
        </ProForm.Item>
      </ProFormGroup>

      <Divider style={{ margin: '24px 0' }} />

      {/* 价格信息分组 */}
      <ProFormGroup title="价格信息">
        <ProFormMoney label="市场价" name="marketPrice" min={0} />
        <ProFormMoney label="销售价" name="price" min={0} />

        <ProFormDigit
          label="税率"
          name="taxRate"
          min={0}
          max={100}
          precision={2}
        />
      </ProFormGroup>

      <Divider style={{ margin: '24px 0' }} />

      {/* 积分信息分组 */}
      <ProFormGroup title="积分信息">
        <ProFormDigit
          name="needPoints"
          label="抵扣积分"
          min={0}
          placeholder="购买时可使用的积分"
        />
        <ProFormDigit
          name="pointsExchangeRate"
          label="积分抵扣规则"
          min={0}
          placeholder="100积分抵扣1元则填100"
        />
        <ProFormDigit
          name="givePoints"
          label="赠送积分"
          min={0}
          placeholder="购买后赠送的积分"
        />
      </ProFormGroup>

      <Divider style={{ margin: '24px 0' }} />

      {/* 库存信息分组 */}
      <ProFormGroup title="库存信息">
        <ProFormDigit name="minPurchaseQuantity" label="最少购买数" min={0} />
        <ProFormDigit name="stockQuantity" label="库存数量" min={0} />
        <ProFormDigit
          name="stockWarningQuantity"
          label="库存预警数量"
          min={0}
        />
      </ProFormGroup>

      <Divider style={{ margin: '24px 0' }} />

      {/* 状态信息分组 */}
      <ProFormGroup title="状态设置">
        <ProFormRadio.Group
          label="推荐"
          name="isRecommended"
          options={[
            { label: '推荐', value: 1 },
            { label: '不推荐', value: 2 },
          ]}
        />
        <ProFormRadio.Group
          label="是否展示"
          name="isDisplayed"
          options={[
            { label: '正常展示', value: 1 },
            { label: '默认隐藏', value: 2 },
          ]}
        />
        <ProFormRadio.Group
          label="状态"
          name="status"
          options={[
            { label: '上架', value: 1 },
            { label: '下架', value: 2 },
          ]}
        />
        <ProFormDigit
          name="sortOrder"
          label="排序"
          min={0}
          placeholder="数字越小越靠前"
        />
      </ProFormGroup>
    </ProForm>
  );
};
